package com.wjm.blog.common.util;


import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * httpUtils
 * @author denghuan
 *
 */
@Slf4j
public class HttpUtils {
	private static String encodeCode = "utf-8";
	
	/**
	 * 设置请求超时时间
	 */
	public static int timeout = 30 * 1000;


	/**
	 * 
	 * @Description: get方法
	 * @param strUrl
	 * @return
	 * @throws IOException    
	 * String    返回类型
	 */
	public static String URLGet(String strUrl) throws IOException {
		return URLGet(strUrl,  encodeCode);
	}
	/**
	 * 
	 * @Description: get方法
	 * @param strUrl
	 * @return
	 * @throws IOException    
	 * String    返回类型
	 */
	public static String URLGet(String strUrl, String urlEncode) throws IOException {
		encodeCode = urlEncode;
		URL url = new URL(strUrl);
		HttpURLConnection con = (HttpURLConnection) url.openConnection();
		con.setUseCaches(false);
		con.setConnectTimeout(timeout);
		con.setReadTimeout(timeout);
		HttpURLConnection.setFollowRedirects(true);
		BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), encodeCode));
		return getStringFromBufferedReader(in);
	}

	/**
	 * 
	 * @Description: post方法
	 * @param strUrl
	 * @return
	 * @throws IOException    
	 * String    返回类型
	 */
	public static String URLPost(String strUrl, Map map) {
		String result = "";
		try {
			result = URLPost(strUrl, map, encodeCode);
		} catch (IOException e) {
			log.error("URLPost :"+strUrl+" -请求异常 ： " + e);
		}
		return result;
	}
	
	public static String URLPost(String strUrl){
		String result = "";
		try {
			result = URLPost(strUrl, "", encodeCode);
		} catch (IOException e) {
			log.error("URLPost :"+strUrl+" -请求异常 ： " + e);
		}
		return result;
	}
	
	/**
	 * 
	 * @Description: post方法
	 * @param strUrl
	 * @return
	 * @throws IOException    
	 * String    返回类型
	 */
	public static String URLPost(String strUrl, Map map, String urlEncode) throws IOException {
	    Long startTime = System.currentTimeMillis();
	    log.info("调用接口开始-url:"+strUrl+"调用参数map:"+map);
		log.info("strUrl:"+strUrl);
	    log.info("map:"+map);
	    log.info("urlEncode:"+urlEncode);
		encodeCode = urlEncode;
		String content = getContentURL(map);
		URL url = new URL(strUrl);
		HttpURLConnection con = (HttpURLConnection) url.openConnection();
		con.setConnectTimeout(timeout);
		con.setReadTimeout(timeout);
		con.setDoInput(true);
		con.setDoOutput(true);
		con.setAllowUserInteraction(false);
		con.setUseCaches(false);
		con.setRequestMethod("POST");
		con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + encodeCode);
		BufferedWriter bout = new BufferedWriter(new OutputStreamWriter(con.getOutputStream()));
		bout.write(content);
		bout.flush();
		bout.close();
		BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), encodeCode));
		Long endTime = System.currentTimeMillis();
		String result = getStringFromBufferedReader(in);
		log.info("程序运行时间： "+(endTime-startTime)+"ms");
		return result;
	}

	public static String URLPost(String strUrl, String content, String urlEncode) throws IOException {
		encodeCode = urlEncode;
		URL url = new URL(strUrl);
		HttpURLConnection con = (HttpURLConnection) url.openConnection();
		con.setConnectTimeout(timeout);
		con.setReadTimeout(timeout);
		con.setDoInput(true);
		con.setDoOutput(true);
		con.setAllowUserInteraction(false);
		con.setUseCaches(false);
		con.setRequestMethod("POST");
		con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + encodeCode);
		BufferedWriter bout = new BufferedWriter(new OutputStreamWriter(con.getOutputStream(), encodeCode));
		bout.write(content);
		bout.flush();
		bout.close();
		BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), encodeCode));
		return getStringFromBufferedReader(in);
	}

	private static String getStringFromBufferedReader(BufferedReader in) throws IOException {
		StringBuffer returnStringBuffer = new StringBuffer();
		char[] tmpbuf = new char[1024];
		int num = in.read(tmpbuf);
		while (num != -1) {
			returnStringBuffer.append(tmpbuf, 0, num);
			num = in.read(tmpbuf);
		}
		in.close();
		return returnStringBuffer.toString();
	}

	public static String getContentURL(Map parameterMap) {
		if ((parameterMap == null) || (parameterMap.keySet().size() == 0)) {
			return "";
		}
		StringBuffer url = new StringBuffer();
		Set keys = parameterMap.keySet();
		for (Iterator i = keys.iterator(); i.hasNext();) {
			String key = String.valueOf(i.next());
			if (parameterMap.containsKey(key)) {
				Object val = parameterMap.get(key);
				String str = val != null ? val.toString() : "";
				try {
					str = URLEncoder.encode(str, encodeCode);
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				url.append(key).append("=").append(str).append("&");
			}
		}
		String strURL = "";
		strURL = url.toString();
		if ("&".equals(String.valueOf(strURL.charAt(strURL.length() - 1)))) {
			strURL = strURL.substring(0, strURL.length() - 1);
		}
		return strURL;
	}

}
